import { http } from "./axiosHttps";


// 仓库管理API配置 - 使用真实的后端API地址
// 根据后端控制器分析，仓库管理API在ManufacturingsERP.API项目中，默认端口应该是7001 (HTTPS)
const warehouseApiUrl = import.meta.env.VITE_WAREHOUSE_API_URL || 'https://localhost:7001/';  // ManufacturingsERP.API项目HTTPS端口

// 通用响应处理函数
const handleApiResponse = (response: any) => {
    // 兼容大小写Code
    const responseCode = response.code || response.Code
    if (responseCode === 200 || responseCode === 'Success') {
        return {
            success: true,
            data: response.data || response.Data,
            message: response.message || response.Message || '操作成功'
        }
    } else {
        return {
            success: false,
            data: null,
            message: response.message || response.Message || '操作失败'
        }
    }
}

const readBasicUrl = import.meta.env.VITE_ReadAPP_API_URL || 'http://localhost:5062/'
const writeBasicUrl = import.meta.env.VITE_WriteAPP_API_URL || 'http://localhost:5063/';
const processBasicUrl = import.meta.env.VITE_Process_API_URL || 'http://localhost:5097/';
const ManufacturingsURL = import.meta.env.VITE_Manufacturing_API_URL || 'http://localhost:5068/';

const ProcessUrl=import.meta.env.VITE_Process_API_URL || 'http://localhost:5145/'

//#region 工序分类管理

//显示工序分类
export const ProcessClassificationShow =(params={})=>{
    return http("get",ProcessUrl + `api/Procedure/ProcessClassificationShow`,{},params);
}
//添加工序分类
export const ProcessClassificationAdd =(data={})=>{
    return http("post",ProcessUrl + `api/Procedure/ProcessClassificationAdd`,data,{});
}
//修改工序分类
export const ProcessClassificationUpdate =(data={})=>{
    return http("put",ProcessUrl + `api/Procedure/ProcessClassificationUpdate`,data,{});
}

//删除工序分类
export const ProcessClassificationDelete =(params={})=>{
    return http("delete",ProcessUrl + `api/Procedure/ProcessClassificationDelete`,{},params);
}

//导出工序分类
export const ProcessClassificationExport =(data={})=>{
    return http("post",ProcessUrl + `api/Procedure/ProcessClassificationExport`,data,{},{
        responseType: 'blob'
    });
}


//#endregion

//#region 工序管理

//显示工序
export const ProcessShow =(params={})=>{
    return http("get",ProcessUrl + `api/Procedure/ProcessShow`,{},params);
}

//添加工序
export const ProcessAdd =(data={})=>{
    return http("post",ProcessUrl + `api/Procedure/ProcessAdd`,data,{});
}

//修改工序
export const ProcessUpdate =(data={})=>{
    return http("put",ProcessUrl + `api/Procedure/ProcessUpdate`,data,{});
}

//删除工序
export const ProcessDelete =(params={})=>{
    return http("delete",ProcessUrl + `api/Procedure/ProcessDelete`,{},params);
}

//根据ID获取工序详情
export const GetProcessById =(params={})=>{
    return http("get",ProcessUrl + `api/Procedure/GetProcessById`,{},params);
}



//获取所有工序分类（用于下拉列表）
export const GetAllProcessClassifications =(params={})=>{
    return http("get",ProcessUrl + `api/Procedure/GetAllProcessClassifications`,{},params);
}

//获取所有部门（用于下拉列表）
export const GetAllDepartments =(params={})=>{
    return http("get",ProcessUrl + `api/Procedure/GetAllDepartments`,{},params);
}

//获取所有用户（用于下拉列表）
export const getAllUsers = (params = {}) => {
    return http("get", readBasicUrl + `api/User/GetUser`, {}, params);
}

//导出工序
export const ProcessExport =(data={})=>{
    return http("post",ProcessUrl + `api/Procedure/ProcessExport`,data,{},{
        responseType: 'blob'
    });
}

//#endregion

//#region 出库单管理

//获取出库单列表
export const getOutboundOrders = (params = {}) => {
    return http("get", ProcessUrl + `api/OutboundOrder/GetOutboundOrders`, {}, params);
}

//根据ID获取出库单详情
export const getOutboundOrderById = (params = {}) => {
    return http("get", ProcessUrl + `api/OutboundOrder/GetOutboundOrderById`, {}, params);
}

//新增出库单
export const createOutboundOrder = (data = {}) => {
    return http("post", ProcessUrl + `api/OutboundOrder/CreateOutboundOrder`, data, {});
}

//更新出库单
export const updateOutboundOrder = (data = {}) => {
    return http("put", ProcessUrl + `api/OutboundOrder/UpdateOutboundOrder`, data, {});
}

//删除出库单
export const deleteOutboundOrder = (params = {}) => {
    return http("delete", ProcessUrl + `api/OutboundOrder/DeleteOutboundOrder`, {}, params);
}

//获取出库单统计信息
export const getOutboundOrderStatistics = (params = {}) => {
    return http("get", ProcessUrl + `api/OutboundOrder/GetStatistics`, {}, params);
}

//获取相关订单（委外、采购等）
export const getRelatedOrders = (params = {}) => {
    return http("get", ProcessUrl + `api/OutboundOrder/GetRelatedOrders`, {}, params);
}

//获取相关物品
export const getRelatedItems = (params = {}) => {
    return http("get", ProcessUrl + `api/OutboundOrder/GetRelatedItems`, {}, params);
}

//#endregion

//#region 附件管理

//添加单个附件
export const AddAttachment = (data = {}) => {
    return http("post", ProcessUrl + `api/Procedure/AddAttachment`, data, {});
}

//批量添加附件
export const AddAttachments = (data = {}) => {
    return http("post", ProcessUrl + `api/Procedure/AddAttachments`, data, {});
}

//根据业务ID获取附件列表
export const GetAttachmentsByEntityId = (params = {}) => {
    return http("get", ProcessUrl + `api/Procedure/GetAttachmentsByEntityId`, {}, params);
}

//删除附件
export const DeleteAttachment = (params = {}) => {
    return http("delete", ProcessUrl + `api/Procedure/DeleteAttachment`, {}, params);
}

//#endregion

//登录
export const login = (params = {}) => {
    return http("get", readBasicUrl + `api/Login/Login`, {}, params);
}

//#region 用户
//显示
export const getUser = (params = {}) => {
    return http("get", readBasicUrl + `api/User/GetUser`, {}, params);
}
//添加
export const addUser = (data = {}) => {
    return http("post", writeBasicUrl + `api/User/AddUser`, data, {});
}
//修改
export const updateUser = (data = {}) => {
    return http("post", writeBasicUrl + `api/User/UpdateUser`, data, {});
}
//修改
export const updateUserState = (data = {}) => {
    return http("post", writeBasicUrl + `api/User/UpdateUserState`, data, {});
}
//删除
export const deleteUser = (data = {}) => {
    return http("post", writeBasicUrl + `api/User/DeleteUser`, data, {});
}
//#endregion

//#region 角色
//获取所有角色
export const getALLRole = (params = {}) => {
    return http("get", readBasicUrl + `api/Role/GetAllRole`, {}, params);
}
//获取角色列表
export const getRole = (params = {}) => {
    return http("get", readBasicUrl + `api/Role/GetRole`, {}, params);
}
//添加角色
export const addRole = (data = {}) => {
    return http("post", writeBasicUrl + `api/Role/AddRole`, data, {});
}
//修改角色
export const updateRole = (data = {}) => {
    return http("post", writeBasicUrl + `api/Role/UpdateRole`, data, {});
}
//修改角色
export const updateRoleState = (data = {}) => {
    return http("post", writeBasicUrl + `api/Role/UpdateRoleState`, data, {});
}
//删除角色
export const deleteRole = (data = {}) => {
    return http("post", writeBasicUrl + `api/Role/DeleteRole`, data, {});
}
//#endregion

//#region  权限
//获取所有权限
export const getPermission = (params = {}) => {
    return http("get", readBasicUrl + `api/Permission/GetPermission`, {}, params);
}
//获取权限级联（增加容错，后端未启动时返回空）
export const getMenu = async (params = {}) => {
    try {
        return await http("get", readBasicUrl + `api/Permission/GetCascadeItem`, {}, params);
    } catch (error) {
        console.warn('GetCascadeItem 未响应，返回空列表')
        return { code: 200, data: [], message: 'ok' }
    }
}
//获取全部权限
export const getAll = (params = {}) => {
    return http("get", readBasicUrl + `api/Permission/GetAllPermission`, {}, params);
}
//添加权限
export const addPermission = (data = {}) => {
    return http("post", writeBasicUrl + `api/Permission/CreatePermission`, data, {});
}
//修改权限
export const updatePermission = (data = {}) => {
    return http("post", writeBasicUrl + `api/Permission/UpdatePermission`, data, {});
}
//删除权限
export const deletePermission =(data={})=>{
    return http("post",writeBasicUrl + `api/Permission/Handle`,data,{});
}
//#endregion

//#region 委外加工
//获取委外加工列表
export const getOutsourcingList = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetList`, {}, params);
}

//根据ID获取委外加工详情
export const getOutsourcingById = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetById`, {}, params);
}

//添加委外加工
export const addOutsourcing = (data = {}) => {
    return http("post", ProcessUrl + `api/OutsourcingProcessing/Add`, data, {});
}

//更新委外加工
export const updateOutsourcing = (data = {}) => {
    return http("put", ProcessUrl + `api/OutsourcingProcessing/Update`, data, {});
}

//删除委外加工
export const deleteOutsourcing = (params = {}) => {
    return http("delete", ProcessUrl + `api/OutsourcingProcessing/Delete`, {}, params);
}

//获取销售订单列表
export const getSalesOrders = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetSalesOrders`, {}, params);
}

//根据销售订单ID获取物品列表
export const getItemsBySalesOrder = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetItemsBySalesOrder`, {}, params);
}

//获取所有物品
export const getAllItems = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetAllItems`, {}, params);
}

//更新委外加工状态
export const updateOutsourcingStatus = (data = {}) => {
    return http("put", ProcessUrl + `api/OutsourcingProcessing/UpdateStatus`, data, {});
}

//获取委外加工附件列表
export const getOutsourcingAttachments = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetAttachments`, {}, params);
}

//添加委外加工附件
export const addOutsourcingAttachment = (data = {}) => {
    return http("post", ProcessUrl + `api/OutsourcingProcessing/AddAttachment`, data, {});
}

//删除委外加工附件
export const deleteOutsourcingAttachment = (params = {}) => {
  return http("delete", ProcessUrl + `api/OutsourcingProcessing/DeleteAttachment`, {}, params);
}

export const exportOutsourcingProcessing = (params = {}) => {
  return http("post", ProcessUrl + `api/OutsourcingProcessing/Export`, params, {}, {
    responseType: 'blob'
  });
}

//获取供应商列表（用于委托单位下拉框）
export const getSuppliers = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetSuppliers`, {}, params);
}

//获取项目列表（用于关联项目下拉框）
export const getProjects = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetProjects`, {}, params);
}

//获取委外加工的生产物品列表
export const getProductionItems = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetProductionItems`, {}, params);
}

//添加委外加工的生产物品
export const addProductionItems = (data = {}) => {
    return http("post", ProcessUrl + `api/OutsourcingProcessing/AddProductionItems`, data, {});
}

//删除委外加工的生产物品
export const deleteProductionItem = (params = {}) => {
    return http("delete", ProcessUrl + `api/OutsourcingProcessing/DeleteProductionItem`, {}, params);
}

//获取委外加工的消耗物品列表
export const getConsumeItems = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetConsumeItems`, {}, params);
}

//添加委外加工的消耗物品
export const addConsumeItems = (data = {}) => {
    return http("post", ProcessUrl + `api/OutsourcingProcessing/AddConsumeItems`, data, {});
}

//删除委外加工的消耗物品
export const deleteConsumeItem = (params = {}) => {
    return http("delete", ProcessUrl + `api/OutsourcingProcessing/DeleteConsumeItem`, {}, params);
}

//获取仓库列表（用于下拉框）
export const getWarehouses = () => {
    return http("get", ProcessUrl + `api/OutsourcingProcessing/GetWarehouses`, {}, {});
}
//#endregion

//#region 委外工单
//获取委外工单列表
export const getOutsourcingWorkOrderList = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingWorkOrder/GetList`, {}, params);
}

//根据ID获取委外工单详情
export const getOutsourcingWorkOrderById = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingWorkOrder/GetById`, {}, params);
}

//添加委外工单
export const addOutsourcingWorkOrder = (data = {}) => {
    return http("post", ProcessUrl + `api/OutsourcingWorkOrder/Add`, data, {});
}

//更新委外工单
export const updateOutsourcingWorkOrder = (data = {}) => {
    return http("put", ProcessUrl + `api/OutsourcingWorkOrder/Update`, data, {});
}

//删除委外工单
export const deleteOutsourcingWorkOrder = (params = {}) => {
    return http("delete", ProcessUrl + `api/OutsourcingWorkOrder/Delete`, {}, params);
}

//获取委外加工列表（用于委外工单选择）
export const getOutsourcingProcessings = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingWorkOrder/GetOutsourcingProcessings`, {}, params);
}

//根据委外加工ID获取物品列表
export const getItemsByOutsourcingProcessing = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingWorkOrder/GetItemsByOutsourcingProcessing`, {}, params);
}

//获取所有物品列表（用于消耗物品选择）
export const getAllItemsForWorkOrder = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingWorkOrder/GetAllItems`, {}, params);
}

//更新委外工单状态
export const updateOutsourcingWorkOrderStatus = (data = {}) => {
    return http("put", ProcessUrl + `api/OutsourcingWorkOrder/UpdateStatus`, data, {});
}

//获取委外工单附件列表
export const getOutsourcingWorkOrderAttachments = (params = {}) => {
    return http("get", ProcessUrl + `api/OutsourcingWorkOrder/GetAttachments`, {}, params);
}

//添加委外工单附件
export const addOutsourcingWorkOrderAttachment = (data = {}) => {
    return http("post", ProcessUrl + `api/OutsourcingWorkOrder/AddAttachment`, data, {});
}

//删除委外工单附件
export const deleteOutsourcingWorkOrderAttachment = (params = {}) => {
  return http("delete", ProcessUrl + `api/OutsourcingWorkOrder/DeleteAttachment`, {}, params);
}

export const exportOutsourcingWorkOrder = (params = {}) => {
  return http("post", ProcessUrl + `api/OutsourcingWorkOrder/Export`, params, {}, {
    responseType: 'blob'
  });
}
//#endregion

//#region 审批管理

// 获取审批实例列表
export const getApprovalInstances = (params = {}) => {
  return http("get", ProcessUrl + `api/ApprovalInstance/GetApprovalInstances`, {}, params);
}

// 获取用户的待审批任务
export const getMyPendingApprovals = (approverId?: number) => {
  const params = approverId ? { approverId } : {}
  return http("get", ProcessUrl + `api/ApprovalInstance/GetMyPendingApprovals`, {}, params);
}

// 根据ID获取审批实例详情
export const getApprovalInstanceById = (params = {}) => {
  return http("get", ProcessUrl + `api/ApprovalInstance/GetApprovalInstance`, {}, params);
}

// 审批/拒绝
export const approveReject = (data = {}) => {
  return http("post", ProcessUrl + `api/ApprovalInstance/ApproveReject`, data, {});
}

// 获取审批流程列表
export const getApprovalProcesses = (params = {}) => {
  return http("get", ProcessUrl + `api/ApprovalProcess/GetApprovalProcesses`, {}, params);
}

// 创建审批流程
export const createApprovalProcess = (data = {}) => {
  return http("post", ProcessUrl + `api/ApprovalProcess/CreateApprovalProcess`, data, {});
}

// 根据ID获取审批流程详情
export const getApprovalProcessById = (params = {}) => {
  return http("get", ProcessUrl + `api/ApprovalProcess/GetApprovalProcess`, {}, params);
}

// 更新审批流程
export const updateApprovalProcess = (data = {}) => {
  return http("put", ProcessUrl + `api/ApprovalProcess/UpdateApprovalProcess`, data, {});
}

// 切换审批流程状态
export const toggleApprovalProcess = (params = {}) => {
  return http("put", ProcessUrl + `api/ApprovalProcess/ToggleApprovalProcess`, {}, params);
}

// 删除审批流程
export const deleteApprovalProcess = (params = {}) => {
  return http("delete", ProcessUrl + `api/ApprovalProcess/DeleteApprovalProcess`, {}, params);
}

// 创建审批实例
export const createApprovalInstance = (data = {}) => {
  return http("post", ProcessUrl + `api/ApprovalInstance/CreateApprovalInstance`, data, {});
}

//#endregion
//#region 物品管理
//获取物品列表
export const getItems = (params = {}) => {
    return http("get", processBasicUrl + `api/Items/GetItemsList`, {}, params);
}
//获取物品分类树形数据
export const getItemCategoryTree =(params={})=>{
    return http("get", processBasicUrl + `api/Items/GetItemCategories`,{},params);
}
//新增物品
export const addItem =(data={})=>{
    return http("post", processBasicUrl + `api/Items/CreateItemss`,data,{});
}
//删除物品
export const deleteItem =(data={})=>{
    return http("post", processBasicUrl + `api/Items/DeleteItems`,data,{});
}
//获取物品详情用于编辑
export const getItemForEdit =(params={})=>{
    return http("get", processBasicUrl + `api/Items/GetItemForEdit`,{},params);
}
//更新物品
export const updateItem =(data={})=>{
    return http("post", processBasicUrl + `api/Items/UpdateItems`,data,{});
}
//#endregion

//#region 工艺流程
//显示工艺流程
export const getProcessFlow = (params = {}) => {
    return http("get", processBasicUrl + `api/ProcessFlows/ShowProcessFlow`, {}, params);
}
//新增工艺流程
export const addProcessFlow = (data = {}) => {
    return http("post", processBasicUrl + `api/ProcessFlows/AddProcessFlow`, data, {});
}
//删除工艺流程
export const deleteProcessFlow = (data = {}) => {
    return http("post", processBasicUrl + `api/ProcessFlows/DeleteProcessFlow`, data, {});
}
//修改工艺流程
export const updateProcessFlow = (data = {}) => {
    return http("post", processBasicUrl + `api/ProcessFlows/UpdateProcessFlow`, data, {});
}
//根据ID获取工艺流程详情
export const getProcessFlowDetailById = (params = {}) => {
    return http("get", processBasicUrl + `api/ProcessFlows/GetProcessFlowById`, {}, params);
}
//#endregion

//#region 人员
//获取人员列表
export const getPersons = (params = {}) => {
    return http("get", "http://localhost:5097/api/Persons/GetPersons", {}, params);
}
//#endregion

//#region 部门
//获取部门列表
export const getDepartments = (params = {}) => {
    return http("get", "http://localhost:5097/api/ProcessFlows/GetDepartment", {}, params);
}
//#endregion



//#region 工序列表
//获取工序列表 (仅支持分页)
export const getProcessList = (params = {}) => {
    return http("get", processBasicUrl + `api/ProcessFlows/GetProcessList`, {}, params);
}
//#endregion

//#region 内部生产
//获取内部生产列表
export const getInternalProductionList = (params={}) => {
    return http("get", processBasicUrl + `api/InternalProduction/GetInternalProductionList`, {}, params);
}
//新增内部生产
export const addInternalProduction = (data={}) => {
    return http("post", processBasicUrl + `api/InternalProduction/AddInternalProduction`, data, {});
}
//删除内部生产
export const deleteInternalProduction = (data={}) => {
    return http("post", processBasicUrl + `api/InternalProduction/DeleteInternalProduction`, data, {});
}
//获取内部生产详情
export const getInternalProductionDetailById = (params={}) => {
    return http("get", processBasicUrl + `api/InternalProduction/GetInternalProductionDetailById`, {}, params);
}

//修改内部生产信息
export const updateInternalProduction = (data: any) => {
    return http("post", processBasicUrl + `api/InternalProduction/UpdateInternalProduction`, data, {});
}


//获取销售订单物品列表
export const getSalesOrderItems = (params = {}) => {
    return http("get", ManufacturingsURL + `api/ProductionPlan/GetSalesOrderItems`, {}, params);
}

//获取物品列表
export const getItemss = (params = {}) => {
    return http("get", ManufacturingsURL + `api/BillOfMaterials/GetItems`, {}, params);
}

//#endregion

//#region 文件上传 - MinIO
//单文件上传
export const uploadFile = (file: File) => {
    const formData = new FormData();
    formData.append('file', file);

    // 使用相对URL，让axios的baseURL来处理
    // 或者使用环境变量配置的URL
    const uploadUrl = import.meta.env.VITE_UPLOAD_API_URL || "http://8.141.112.218:5080/api/FileUpload/UploadFile";
    
    // 对于文件上传，让浏览器自动设置Content-Type
    // 不手动设置Content-Type，让FormData自动处理
    return http("post", uploadUrl, formData, {}, {});
}

//多文件上传
export const uploadFiles = (files: File[]) => {
    const formData = new FormData();
    files.forEach((file: File) => {
        formData.append('files', file);
    });

    const uploadUrl = import.meta.env.VITE_UPLOAD_API_URL || "http://8.141.112.218:5080/api/FileUpload/UploadFiles";
    return http("post", uploadUrl, formData, {}, {});
}
//#endregion